package server_monitor

import (
	"github.com/shirou/gopsutil/v4/cpu"
	"github.com/shirou/gopsutil/v4/disk"
	"github.com/shirou/gopsutil/v4/mem"
	"runtime"
)

type ServerMonitorData struct {
	Runtime struct {
		GoVersion string `json:"goVersion"`
		Os        string `json:"os"`
		Arch      string `json:"arch"`
	} `json:"runtime"`
	Cpu struct {
		Manufacturer       string  `json:"manufacturer"`
		Brand              string  `json:"brand"`
		PhysicalCores      int     `json:"physicalCores"`
		Model              int     `json:"model"`
		Speed              float64 `json:"speed"`
		RawCurrentLoad     float64 `json:"rawCurrentLoad"`
		RawCurrentLoadIdle float64 `json:"rawCurrentLoadIdle"`
		CoresLoad          []struct {
			RawLoad     float64 `json:"rawLoad"`
			RawLoadIdle float64 `json:"rawLoadIdle"`
		} `json:"coresLoad"`
	} `json:"cpu"`
	Disk struct {
		Size      uint64 `json:"size"`
		Used      uint64 `json:"used"`
		Available uint64 `json:"available"`
	} `json:"disk"`
	Memory struct {
		Total     uint64 `json:"total"`
		Available uint64 `json:"available"`
	} `json:"memory"`
}
type ServerMonitorService struct {
}

func NewServerMonitorService() *ServerMonitorService {
	return &ServerMonitorService{}
}

func (s *ServerMonitorService) GetServerMonitorData() ServerMonitorData {
	data := ServerMonitorData{}

	data.Runtime.GoVersion = runtime.Version()
	data.Runtime.Os = runtime.GOOS
	data.Runtime.Arch = runtime.GOARCH

	// 获取 CPU 信息
	cpuInfo, err := cpu.Info()
	if err == nil && len(cpuInfo) > 0 {
		data.Cpu.Manufacturer = cpuInfo[0].VendorID
		data.Cpu.Brand = cpuInfo[0].ModelName
		data.Cpu.PhysicalCores, _ = cpu.Counts(false)
		data.Cpu.Speed = cpuInfo[0].Mhz
	}
	cpuPercent, err := cpu.Percent(0, false)
	if err == nil {
		data.Cpu.RawCurrentLoad = cpuPercent[0]
	}
	data.Cpu.RawCurrentLoadIdle = 100 - data.Cpu.RawCurrentLoad
	coresLoad := make([]struct {
		RawLoad     float64 `json:"rawLoad"`
		RawLoadIdle float64 `json:"rawLoadIdle"`
	}, data.Cpu.PhysicalCores)
	for i := 0; i < len(coresLoad); i++ {
		corePercent, err := cpu.Percent(0, true)
		if err == nil && i < len(corePercent) {
			coresLoad[i].RawLoad = corePercent[i]
			coresLoad[i].RawLoadIdle = 100 - corePercent[i]
		}
	}
	data.Cpu.CoresLoad = coresLoad

	// 获取磁盘信息
	diskUsage, err := disk.Usage("/")
	if err == nil {
		data.Disk.Size = diskUsage.Total
		data.Disk.Used = diskUsage.Used
		data.Disk.Available = diskUsage.Free
	}

	// 获取内存信息
	memInfo, err := mem.VirtualMemory()
	if err == nil {
		data.Memory.Total = memInfo.Total
		data.Memory.Available = memInfo.Available
	}

	return data
}
